package com.zyndev.sanchi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zyndev.sanchi.domain.Action;
import com.zyndev.sanchi.domain.Mapping;
import com.zyndev.sanchi.util.ClassCommentInfo;
import com.zyndev.sanchi.util.ClassScanner;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

import static com.zyndev.sanchi.util.JavaDocUtil.extractJavaDoc;
import static com.zyndev.sanchi.util.MappingUtil.getMappings;

/**
 * @author 张瑀楠 zyndev@gmail.com
 * @version 0.0.1
 */
public class Core {

    public String convert(String sourcePath, String backPackage) throws IOException, ClassNotFoundException {

        // 源码路径
        // 扫描包，得到所有的class
        Set<Class<?>> classes = new ClassScanner().getPackageAllClasses(backPackage, true);

        List<Action> actionList = new ArrayList<>();
        System.out.println("开始处理" + classes);
        // 处理所有的class
        for (Class<?> clazz : classes) {
            if (clazz.getAnnotation(RestController.class) != null || clazz.getAnnotation(Controller.class) != null) {
                System.out.println("开始处理");
                // 获取javadoc信息
                List<ClassCommentInfo> classCommentInfoList = extractJavaDoc(clazz, sourcePath);
                Map<String, ClassCommentInfo> classCommentInfoMap = new HashMap<>();
                String author = null;
                for (ClassCommentInfo classCommentInfo : classCommentInfoList) {
                    author = classCommentInfo.getAuthor();
                    classCommentInfoMap.put(classCommentInfo.getName(), classCommentInfo);
                }

                List<Mapping> mappingList = getMappings(clazz, classCommentInfoMap);

                Action action = new Action();
                action.setAuthor(author);
                action.setName(clazz.getName());
                action.setSimpleName(clazz.getSimpleName());
                action.setMappingList(mappingList);

                actionList.add(action);
            }
        }

        return JSON.toJSONString(actionList, SerializerFeature.DisableCircularReferenceDetect);
    }
}
